<template>
  <div class="human-service-container">
    <!-- 顶部状态栏 -->
    <div class="status-bar">
      <span class="status-text">12:00</span>
      <div class="status-icons">
        <span class="icon">📶</span>
        <span class="icon">🔋</span>
      </div>
    </div>

    <!-- 头部导航 -->
    <div class="service-header">
      <button class="back-btn" @click="$router.back()">← 返回</button>
      <h2 class="header-title">人工客服</h2>
      <div class="header-right">
        <button class="start-btn" @click="startHumanService" :disabled="loading">
          {{ loading ? '连接中...' : '联系客服' }}
        </button>
      </div>
    </div>

    <!-- 主内容区：左边栏 + 聊天区 -->
    <div class="main-content">
      <!-- 左边栏：咨询列表 -->
      <div class="sidebar">
        <div class="sidebar-header">
          <h3>客服会话</h3>
          <span class="count-badge">{{ consultationList.length }}</span>
        </div>
        <div class="consultation-list">
          <div 
            v-for="consultation in consultationList" 
            :key="consultation.room_id"
            :class="['consultation-item', { active: currentRoomId === consultation.room_id }]"
            @click="enterChatRoom(consultation)"
          >
            <div class="avatar">
              <span v-if="!consultation.avatar">👤</span>
              <img v-else :src="consultation.avatar" alt="用户头像" />
            </div>
            <div class="info">
              <div class="name">用户 {{ consultation.user_id }}</div>
              <div class="time">{{ formatTime(consultation.created_at) }}</div>
              <div class="status" :class="consultation.status">
                {{ getStatusText(consultation.status) }}
              </div>
            </div>
          </div>
          <div v-if="consultationList.length === 0" class="empty-tip">
            <p>暂无客服会话</p>
            <p class="tip">点击"联系客服"开始对话</p>
          </div>
        </div>
      </div>

      <!-- 右侧：聊天区域 -->
      <div class="chat-area">
        <div v-if="!currentRoomId" class="welcome-screen">
          <div class="welcome-icon">👨‍💼</div>
          <h3>欢迎使用人工客服</h3>
          <p>点击"联系客服"与人工客服对话</p>
        </div>

        <div v-else class="chat-room">
          <!-- 聊天室头部 -->
          <div class="chat-header">
            <div class="chat-title">
              <span class="avatar-small">👤</span>
              <span>与用户 {{ currentUserId }} 的对话</span>
            </div>
            <div class="connection-status" :class="{ connected: chatRoomConnected }">
              <span class="status-dot"></span>
              {{ chatRoomConnected ? '已连接' : '连接中...' }}
            </div>
          </div>

          <!-- 消息列表 -->
          <div class="messages-container" ref="messagesContainer">
            <div 
              v-for="(message, index) in chatMessages" 
              :key="index"
              :class="['message-item', message.type]"
            >
              <div class="avatar">
                <span v-if="message.type === 'bot'">👨‍💼</span>
                <span v-else>👤</span>
              </div>
              <div class="message-content">
                <div class="message-bubble" :class="message.type">
                  <p>{{ message.content }}</p>
                </div>
                <div class="message-time">{{ message.time }}</div>
              </div>
            </div>
            <div v-if="chatLoading" class="typing-indicator">
              <span></span><span></span><span></span>
            </div>
          </div>

          <!-- 输入区域 -->
          <div class="input-area">
            <input 
              v-model="inputText"
              type="text"
              placeholder="输入消息..."
              class="message-input"
              @keyup.enter="sendMessage"
              :disabled="!chatRoomConnected"
            />
            <button 
              class="send-btn" 
              @click="sendMessage" 
              :disabled="!inputText.trim() || !chatRoomConnected || chatLoading"
            >
              发送
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
// 复用 OnlineConsultation.vue 的逻辑，只是标题和按钮文字不同
import { ref, onMounted, onBeforeUnmount, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import apiClient from '@/api/axios'

const router = useRouter()

// 数据状态
const consultationList = ref([])
const currentRoomId = ref(null)
const currentServiceId = ref(null)
const currentUserId = ref(null)
const chatMessages = ref([])
const inputText = ref('')
const loading = ref(false)
const chatLoading = ref(false)
const chatRoomConnected = ref(false)

// WebSocket连接
const serviceWs = ref(null) // 客服WebSocket连接（基于后端websocket.py）
const chatRoomWs = ref(null) // 聊天室WebSocket连接（复用serviceWs）
const messagesContainer = ref(null)

// 获取当前时间
const getCurrentTime = () => {
  const now = new Date()
  const hours = String(now.getHours()).padStart(2, '0')
  const minutes = String(now.getMinutes()).padStart(2, '0')
  return `${hours}:${minutes}`
}

// 格式化时间
const formatTime = (timestamp) => {
  if (!timestamp) return ''
  const date = new Date(timestamp)
  const now = new Date()
  const diff = now - date
  
  if (diff < 60000) return '刚刚'
  if (diff < 3600000) return `${Math.floor(diff / 60000)}分钟前`
  if (diff < 86400000) return `${Math.floor(diff / 3600000)}小时前`
  
  return date.toLocaleDateString('zh-CN', { month: 'short', day: 'numeric' })
}

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    pending: '待处理',
    accepted: '进行中',
    rejected: '已拒绝',
    completed: '已结束'
  }
  return statusMap[status] || '未知'
}

// 初始化客服WebSocket连接（基于后端websocket.py实现）
// 注意：人工客服页面应该作为客服连接，连接路径：ws://host/ws/chat/service{service_id}
const initServiceWebSocket = async () => {
  // 如果已经连接，直接返回
  if (serviceWs.value && serviceWs.value.readyState === WebSocket.OPEN) {
    console.log('[人工客服] WebSocket已连接，无需重新连接')
    return Promise.resolve()
  }
  
  return new Promise((resolve, reject) => {
    try {
      // 客服ID，从localStorage获取或使用默认值
      const serviceId = localStorage.getItem('service_id') || '1001'
      localStorage.setItem('service_id', serviceId)
      
      console.log('[人工客服] 开始连接WebSocket，客服ID:', serviceId)
      
      // 连接后端websocket.py的WebSocket（路径格式：ws://host/ws/chat/service{service_id}）
      const wsUrl = `ws://127.0.0.1:8000/ws/chat/service${serviceId}`
      console.log('[人工客服] 连接WebSocket:', wsUrl)
      const ws = new WebSocket(wsUrl)
      
      ws.onopen = () => {
        console.log('[人工客服] WebSocket连接成功，后端将自动推送待处理请求')
        serviceWs.value = ws
        loading.value = false
        resolve()
      }
      
      ws.onerror = (error) => {
        console.error('[人工客服] WebSocket连接错误:', error)
        loading.value = false
        reject(error)
      }
      
      ws.onmessage = (event) => {
        const message = JSON.parse(event.data)
        handleServiceWebSocketMessage(message)
      }
      
      ws.onclose = () => {
        console.log('[人工客服] WebSocket连接关闭')
        serviceWs.value = null
        chatRoomConnected.value = false
      }
    } catch (error) {
      console.error('[人工客服] 初始化WebSocket失败:', error)
      loading.value = false
      reject(error)
    }
  })
}

// 开始人工客服（基于后端websocket.py实现）
const startHumanService = async () => {
  if (loading.value) return
  
  try {
    loading.value = true
    
    // 先检查是否已有咨询会话（可能从在线咨询页面创建）
    loadConsultationsFromStorage()
    
    // 确保客服WebSocket已连接
    await initServiceWebSocket()
    
    // 后端websocket.py在客服连接时会自动推送所有待处理请求
    // 所以这里不需要手动发送消息
    console.log('[人工客服] WebSocket连接完成，等待后端推送咨询请求列表')
    
  } catch (error) {
    console.error('[人工客服] 错误:', error)
    alert('连接失败：' + (error.message || '网络连接失败'))
    loading.value = false
  }
}

// 处理客服WebSocket消息（基于后端websocket.py实现）
const handleServiceWebSocketMessage = (message) => {
  console.log('[人工客服] 收到WebSocket消息:', message)
  
  // 处理聊天消息（后端websocket.py通过房间组广播）
  if (message.type === 'chat') {
    // 实时推送：聊天消息立即显示，无需刷新
    const roomId = message.room_id || currentRoomId.value
    if (roomId && roomId === currentRoomId.value) {
      // 从room_id解析user_id和service_id
      const parts = roomId.split('_')
      const serviceId = parts.length >= 2 ? parts.slice(1).join('_') : null
      const userId = localStorage.getItem('user_id') || 'user_' + Date.now()
      const currentServiceId = localStorage.getItem('service_id') || '1001'
      
      // 判断发送者
      const isServiceMessage = serviceId && message.sender === serviceId
      const isCurrentServiceMessage = message.sender === `service_${currentServiceId}`
      const isUserMessage = message.sender === userId || (message.sender && message.sender.startsWith('user_'))
      
      // 判断消息类型：
      // 1. 如果是客服消息，显示在右侧（客服自己发送的）
      // 2. 如果是用户消息，显示在左侧（用户发送的）
      let messageType
      if (isCurrentServiceMessage || isServiceMessage) {
        messageType = 'user' // 客服消息在右侧
      } else if (isUserMessage) {
        messageType = 'bot' // 用户消息在左侧
      } else {
        messageType = 'bot' // 默认左侧
      }
      
      const newMessage = {
        type: messageType,
        content: message.content,
        sender: message.sender,
        timestamp: message.timestamp,
        time: message.timestamp ? new Date(message.timestamp).toLocaleTimeString('zh-CN', { 
          hour: '2-digit', 
          minute: '2-digit' 
        }) : getCurrentTime()
      }
      
      // 实时推送：检查是否已经存在相同的消息（避免重复添加）
      const messageTime = message.timestamp ? new Date(message.timestamp).getTime() : Date.now()
      const existing = chatMessages.value.find(msg => {
        if (msg.content === newMessage.content && msg.sender === newMessage.sender) {
          const msgTime = msg.timestamp ? new Date(msg.timestamp).getTime() : 0
          return Math.abs(messageTime - msgTime) < 1000
        }
        return false
      })
      
      if (!existing) {
        // 实时推送：立即添加到消息列表，无需刷新
        chatMessages.value.push(newMessage)
        console.log('[实时推送] 聊天消息已实时显示:', newMessage.content)
        
        // 保存到localStorage
        saveChatHistory()
        
        // 通知其他页面有新消息
        window.dispatchEvent(new CustomEvent('newChatMessage', {
          detail: {
            room_id: roomId,
            message: newMessage
          }
        }))
        
        // 实时推送：立即滚动到底部，显示新消息
        chatLoading.value = false
        nextTick(() => scrollToBottom())
      }
    }
    return
  }
  
  // 处理咨询列表（后端websocket.py在客服连接时自动推送）
  if (message.type === 'consultation_list') {
    loading.value = false
    console.log('[人工客服] 收到咨询列表:', message.data)
    
    // 添加所有待处理的咨询请求到列表
    if (message.data && Array.isArray(message.data)) {
      message.data.forEach(consultation => {
        const existing = consultationList.value.find(item => item.room_id === consultation.room_id)
        if (!existing) {
          consultationList.value.push({
            ...consultation,
            avatar: null,
            lastMessage: null,
            unreadCount: 0
          })
        }
      })
    }
    return
  }
  
  // 处理新咨询请求（后端websocket.py实时推送）
  if (message.type === 'new_consultation') {
    console.log('[人工客服] 收到新咨询请求:', message.data)
    
    const consultationData = message.data
    const existing = consultationList.value.find(item => item.room_id === consultationData.room_id)
    if (!existing) {
      consultationList.value.push({
        ...consultationData,
        avatar: null,
        lastMessage: null,
        unreadCount: 0
      })
      
      // 触发自定义事件，通知其他页面
      window.dispatchEvent(new CustomEvent('consultationCreated', { 
        detail: consultationData 
      }))
    }
    return
  }
  
  // 处理错误消息
  if (message.type === 'error') {
    loading.value = false
    alert('创建客服请求失败：' + (message.message || '未知错误'))
    return
  }
  
  // 处理咨询已接受
  if (message.type === 'consultation_accepted') {
    // 客服已接受咨询（原有逻辑保持不变）
    const { room_id } = message.data
    const consultation = consultationList.value.find(item => item.room_id === room_id)
    if (consultation) {
      consultation.status = 'accepted'
      
      // 如果当前在这个聊天室，显示消息
      if (currentRoomId.value === room_id) {
        chatMessages.value.push({
          type: 'system',
          content: '客服已接受您的咨询',
          time: getCurrentTime()
        })
        nextTick(() => scrollToBottom())
      }
    }
    
    // 通知其他页面
    window.dispatchEvent(new CustomEvent('consultationAccepted', { detail: { room_id } }))
  }
}

// 保存咨询到localStorage
const saveConsultationToStorage = (consultation) => {
  try {
    const key = `consultation_${consultation.user_id}`
    localStorage.setItem(key, JSON.stringify(consultation))
  } catch (e) {
    console.error('保存咨询失败:', e)
  }
}

// 从localStorage加载咨询列表
const loadConsultationsFromStorage = () => {
  try {
    const userId = localStorage.getItem('user_id') || 'user_' + Date.now()
    const key = `consultation_${userId}`
    const data = localStorage.getItem(key)
    if (data) {
      const consultation = JSON.parse(data)
      const existing = consultationList.value.find(item => item.room_id === consultation.room_id)
      if (!existing) {
        consultationList.value.push({
          ...consultation,
          avatar: null,
          lastMessage: null,
          unreadCount: 0
        })
      }
    }
  } catch (e) {
    console.error('加载咨询失败:', e)
  }
}

// 进入聊天室
const enterChatRoom = async (consultation) => {
  currentRoomId.value = consultation.room_id
  currentServiceId.value = consultation.service_id
  currentUserId.value = consultation.user_id
  
  // 保存当前聊天室ID到localStorage（供其他页面使用）
  localStorage.setItem('current_chat_room_id', consultation.room_id)
  
  // 如果已经在同一个聊天室，不重复连接
  if (chatRoomWs.value && chatRoomConnected.value && currentRoomId.value === consultation.room_id) {
    console.log('[人工客服] 已在当前聊天室，无需重新连接')
    return
  }
  
  // 加载历史消息（从localStorage或后端获取）
  loadChatHistory(consultation.room_id)
  
  // 连接到聊天室
  await connectToChatRoom(consultation.room_id, consultation.user_id, 'user')
}

// 加载聊天历史
const loadChatHistory = (roomId) => {
  try {
    const historyKey = `chat_history_${roomId}`
    const history = localStorage.getItem(historyKey)
    if (history) {
      const messages = JSON.parse(history)
      // 转换消息类型：联系客服页面（客服视角）- 客服消息在右侧，用户消息在左侧
      // 从room_id解析service_id
      const parts = roomId.split('_')
      const serviceId = parts.length >= 2 ? parts.slice(1).join('_') : null
      
      const userId = localStorage.getItem('user_id') || 'user_' + Date.now()
      
      chatMessages.value = messages.map(msg => {
        // 如果消息有sender，根据sender和fromHumanService标识判断
        if (msg.sender && serviceId) {
          const isServiceMessage = msg.sender === serviceId
          const isFromHumanService = msg.fromHumanService === true
          const isCurrentUserMessage = msg.sender === userId
          
          let messageType
          if (isServiceMessage) {
            messageType = 'user' // 客服消息在右侧
          } else if (isFromHumanService && isCurrentUserMessage) {
            messageType = 'user' // 用户在联系客服页面发送的消息在右侧
          } else {
            messageType = 'bot' // 用户在在线咨询页面发送的消息在左侧
          }
          
          return { ...msg, type: messageType }
        }
        // 如果没有sender，保持原样（兼容旧数据）
        return msg
      })
      nextTick(() => scrollToBottom())
    } else {
      // 如果没有历史，清空消息
      chatMessages.value = []
    }
  } catch (e) {
    console.error('加载聊天历史失败:', e)
    chatMessages.value = []
  }
}

// 保存聊天历史
const saveChatHistory = () => {
  if (currentRoomId.value && chatMessages.value.length > 0) {
    try {
      const historyKey = `chat_history_${currentRoomId.value}`
      localStorage.setItem(historyKey, JSON.stringify(chatMessages.value))
    } catch (e) {
      console.error('保存聊天历史失败:', e)
    }
  }
}

// 连接到聊天室 - 基于后端websocket.py实现
// 注意：后端websocket.py中，客服连接时已经加入了客服房间组
// 但聊天消息是通过聊天室房间组广播的，所以需要确保客服WebSocket连接存在
const connectToChatRoom = async (roomId, userId, identity) => {
  return new Promise(async (resolve, reject) => {
    try {
      // 后端websocket.py中，客服连接时已经连接
      // 所以这里不需要重新连接，只需要确保serviceWs连接存在
      if (!serviceWs.value || serviceWs.value.readyState !== WebSocket.OPEN) {
        console.log('[聊天室] 客服WebSocket未连接，重新连接...')
        // 如果客服WebSocket未连接，重新连接
        try {
          await initServiceWebSocket()
          if (serviceWs.value && serviceWs.value.readyState === WebSocket.OPEN) {
            chatRoomWs.value = serviceWs.value // 复用客服WebSocket连接
            chatRoomConnected.value = true
            console.log('[聊天室] 已连接到聊天室:', roomId)
            resolve(serviceWs.value)
          } else {
            reject(new Error('客服WebSocket连接失败'))
          }
        } catch (error) {
          console.error('[聊天室] 重新连接失败:', error)
          reject(error)
        }
        return
      }
      
      // 复用客服WebSocket连接
      // 注意：后端websocket.py中，聊天消息通过房间组广播
      // 但客服连接时只加入了客服房间组，没有加入聊天室房间组
      // 所以可能需要通过后端修改或前端重新连接来加入聊天室
      // 这里先复用连接，消息应该还是能通过客服房间组接收
      chatRoomWs.value = serviceWs.value
      chatRoomConnected.value = true
      console.log('[聊天室] 已连接到聊天室:', roomId)
      resolve(serviceWs.value)
      
    } catch (error) {
      console.error('[聊天室] 连接失败:', error)
      reject(error)
    }
  })
}

// 发送消息
const sendMessage = async () => {
  if (!inputText.value.trim() || !chatRoomConnected.value || chatLoading.value) return
  
  const content = inputText.value.trim()
  const userId = localStorage.getItem('user_id') || 'user_' + Date.now()
  
  // 添加到消息列表
  // 联系客服页面：用户在联系客服页面发送的消息应该显示在右侧（用户自己的消息）
  const newMessage = {
    type: 'user', // 联系客服页面：用户在联系客服页面发送的消息显示在右侧（这是用户自己发送的消息）
    content: content,
    sender: userId,
    fromHumanService: true, // 标识消息来自联系客服页面
    time: getCurrentTime()
  }
  
  chatMessages.value.push(newMessage)
  
  // 保存到localStorage
  saveChatHistory()
  
  // 通知其他页面有新消息
  window.dispatchEvent(new CustomEvent('newChatMessage', {
    detail: {
      room_id: currentRoomId.value,
      message: newMessage
    }
  }))
  
  inputText.value = ''
  chatLoading.value = true
  
  await nextTick()
  scrollToBottom()
  
  // 实时推送：发送到聊天室WebSocket（基于后端websocket.py实现）
  if (chatRoomWs.value && chatRoomWs.value.readyState === WebSocket.OPEN) {
    // 后端websocket.py期望的消息格式：{"type": "chat", "content": "消息内容", "sender": "service_1001"}
    const serviceId = localStorage.getItem('service_id') || '1001'
    chatRoomWs.value.send(JSON.stringify({
      type: 'chat',
      content: content,
      sender: `service_${serviceId}` // 发送者ID，用于后端识别和转发
    }))
    console.log('[实时推送] 消息已发送，等待服务器实时转发给对方')
    chatLoading.value = false
  } else {
    chatLoading.value = false
    alert('连接已断开，请重新进入聊天室')
  }
}

// 滚动到底部
const scrollToBottom = () => {
  if (messagesContainer.value) {
    messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight
  }
}

// 初始化用户WebSocket（接收咨询状态更新和发送咨询请求）
const initUserWebSocket = () => {
  const userId = localStorage.getItem('user_id') || 'user_' + Date.now()
  
  try {
    const wsUrl = `ws://127.0.0.1:8000/ws/user/${userId}`
    const ws = new WebSocket(wsUrl)
    
    ws.onopen = () => {
      console.log('[用户WebSocket] 连接成功')
      userWs.value = ws
    }
    
    ws.onmessage = (event) => {
      const message = JSON.parse(event.data)
      handleUserWebSocketMessage(message)
    }
    
    ws.onerror = (error) => {
      console.error('[用户WebSocket] 错误:', error)
    }
    
    ws.onclose = () => {
      console.log('[用户WebSocket] 连接关闭')
      userWs.value = null
    }
    
  } catch (error) {
    console.error('[用户WebSocket] 初始化失败:', error)
  }
}

// 监听跨页面的咨询创建事件
const handleConsultationCreated = (event) => {
  const consultation = event.detail
  const existing = consultationList.value.find(item => item.room_id === consultation.room_id)
  if (!existing) {
    consultationList.value.push({
      ...consultation,
      avatar: null,
      lastMessage: null,
      unreadCount: 0
    })
  }
}

// 监听跨页面的新消息事件
const handleNewChatMessage = (event) => {
  const { room_id, message } = event.detail
  
  // 如果当前在这个聊天室，添加消息
  if (currentRoomId.value === room_id) {
    // 转换消息类型：联系客服页面（客服视角）- 客服消息在右侧，用户消息在左侧
    const convertedMessage = { ...message }
    
    // 从room_id解析service_id
    const parts = room_id.split('_')
    const serviceId = parts.length >= 2 ? parts.slice(1).join('_') : null
    
    if (message.sender && serviceId) {
      const userId = localStorage.getItem('user_id') || 'user_' + Date.now()
      const isServiceMessage = message.sender === serviceId
      const isFromHumanService = message.fromHumanService === true
      const isCurrentUserMessage = message.sender === userId
      
      // 判断消息类型
      if (isServiceMessage) {
        convertedMessage.type = 'user' // 客服消息在右侧
      } else if (isFromHumanService && isCurrentUserMessage) {
        convertedMessage.type = 'user' // 用户在联系客服页面发送的消息在右侧
      } else {
        convertedMessage.type = 'bot' // 用户在在线咨询页面发送的消息在左侧
      }
    }
    
    // 避免重复添加（检查最后一条消息）
    const lastMsg = chatMessages.value[chatMessages.value.length - 1]
    if (!lastMsg || lastMsg.content !== convertedMessage.content || lastMsg.time !== convertedMessage.time) {
      chatMessages.value.push(convertedMessage)
      saveChatHistory()
      nextTick(() => scrollToBottom())
    }
  }
}

// 生命周期
onMounted(async () => {
  // 加载已保存的咨询
  loadConsultationsFromStorage()
  
  // 监听跨页面事件
  window.addEventListener('consultationCreated', handleConsultationCreated)
  window.addEventListener('newChatMessage', handleNewChatMessage)
  
  // 基于后端websocket.py实现：页面加载时自动连接客服WebSocket
  // 后端会在客服连接时自动推送所有待处理请求
  try {
    await startHumanService()
    console.log('[人工客服] WebSocket连接初始化完成')
  } catch (error) {
    console.error('[人工客服] WebSocket连接初始化失败:', error)
  }
  
  // 检查是否有正在进行的聊天室，自动连接
  // 等待WebSocket连接建立后再进入聊天室
  const savedRoomId = localStorage.getItem('current_chat_room_id')
  if (savedRoomId && consultationList.value.length > 0) {
    const consultation = consultationList.value.find(item => item.room_id === savedRoomId)
    if (consultation) {
      // 延迟一下，确保WebSocket连接建立
      setTimeout(async () => {
        try {
          await enterChatRoom(consultation)
        } catch (error) {
          console.error('[人工客服] 自动进入聊天室失败:', error)
        }
      }, 1000)
    }
  }
  
  scrollToBottom()
})

onBeforeUnmount(() => {
  // 保存聊天历史
  saveChatHistory()
  
  // 移除事件监听
  window.removeEventListener('consultationCreated', handleConsultationCreated)
  window.removeEventListener('newChatMessage', handleNewChatMessage)
  
  if (serviceWs.value) {
    serviceWs.value.close()
  }
  // chatRoomWs复用serviceWs，不需要单独关闭
})
</script>

<style scoped>
/* 复用 OnlineConsultation.vue 的样式 */
.human-service-container {
  width: 100vw;
  height: 100vh;
  background: #f5f5f5;
  display: flex;
  flex-direction: column;
}

.status-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 5px 15px;
  background: white;
  font-size: 12px;
}

.status-icons {
  display: flex;
  gap: 5px;
}

.service-header {
  background: white;
  padding: 15px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  border-bottom: 1px solid #f0f0f0;
}

.back-btn {
  background: none;
  border: none;
  font-size: 14px;
  cursor: pointer;
  padding: 5px 10px;
  color: #333;
}

.header-title {
  font-size: 18px;
  font-weight: bold;
  color: #333;
  margin: 0;
  flex: 1;
  text-align: center;
}

.header-right {
  width: 100px;
  display: flex;
  justify-content: flex-end;
}

.start-btn {
  padding: 8px 16px;
  background: #007AFF;
  color: white;
  border: none;
  border-radius: 20px;
  font-size: 13px;
  cursor: pointer;
  transition: all 0.3s;
}

.start-btn:hover:not(:disabled) {
  background: #0056b3;
}

.start-btn:disabled {
  background: #ccc;
  cursor: not-allowed;
}

.main-content {
  flex: 1;
  display: flex;
  overflow: hidden;
}

.sidebar {
  width: 280px;
  background: white;
  border-right: 1px solid #f0f0f0;
  display: flex;
  flex-direction: column;
  min-height: 0; /* 在 flex 布局中，需要设置 min-height: 0 才能让滚动条正常工作 */
  overflow: hidden;
}

.sidebar-header {
  padding: 15px;
  border-bottom: 1px solid #f0f0f0;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.sidebar-header h3 {
  margin: 0;
  font-size: 16px;
  color: #333;
}

.count-badge {
  background: #007AFF;
  color: white;
  padding: 2px 8px;
  border-radius: 10px;
  font-size: 12px;
}

.consultation-list {
  flex: 1;
  overflow-y: auto;
  overflow-x: hidden;
  min-height: 0; /* 在 flex 布局中，需要设置 min-height: 0 才能让滚动条正常工作 */
}

/* 确保滚动条可见（Webkit浏览器） */
.consultation-list::-webkit-scrollbar {
  width: 8px;
}

.consultation-list::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 4px;
}

.consultation-list::-webkit-scrollbar-thumb {
  background: #888;
  border-radius: 4px;
}

.consultation-list::-webkit-scrollbar-thumb:hover {
  background: #555;
}

.consultation-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 15px;
  cursor: pointer;
  transition: all 0.2s;
  border-bottom: 1px solid #f5f5f5;
}

.consultation-item:hover {
  background: #f5f5f5;
}

.consultation-item.active {
  background: #e3f2fd;
}

.consultation-item .avatar {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  background: #e3f2fd;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
  flex-shrink: 0;
}

.consultation-item .info {
  flex: 1;
  min-width: 0;
}

.consultation-item .name {
  font-size: 14px;
  font-weight: 500;
  color: #333;
  margin-bottom: 4px;
}

.consultation-item .time {
  font-size: 12px;
  color: #999;
  margin-bottom: 4px;
}

.consultation-item .status {
  font-size: 11px;
  padding: 2px 6px;
  border-radius: 4px;
  display: inline-block;
}

.consultation-item .status.pending {
  background: #fff3cd;
  color: #856404;
}

.consultation-item .status.accepted {
  background: #d4edda;
  color: #155724;
}

.empty-tip {
  padding: 40px 20px;
  text-align: center;
  color: #999;
}

.empty-tip .tip {
  font-size: 12px;
  margin-top: 10px;
}

.chat-area {
  flex: 1;
  display: flex;
  flex-direction: column;
  background: #f5f5f5;
  min-height: 0; /* 在 flex 布局中，需要设置 min-height: 0 才能让滚动条正常工作 */
  overflow: hidden;
}

.welcome-screen {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: #999;
}

.welcome-icon {
  font-size: 64px;
  margin-bottom: 20px;
}

.welcome-screen h3 {
  margin: 0 0 10px 0;
  color: #666;
}

.welcome-screen p {
  margin: 0;
  font-size: 14px;
}

.chat-room {
  flex: 1;
  display: flex;
  flex-direction: column;
  background: white;
  min-height: 0; /* 在 flex 布局中，需要设置 min-height: 0 才能让滚动条正常工作 */
  overflow: hidden;
}

.chat-header {
  padding: 15px;
  border-bottom: 1px solid #f0f0f0;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.chat-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 16px;
  font-weight: 500;
  color: #333;
}

.avatar-small {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  background: #e3f2fd;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 16px;
}

.connection-status {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 12px;
  color: #999;
}

.connection-status.connected {
  color: #28a745;
}

.status-dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background: #999;
}

.connection-status.connected .status-dot {
  background: #28a745;
}

.messages-container {
  flex: 1;
  overflow-y: auto;
  overflow-x: hidden;
  padding: 15px;
  background: #f5f5f5;
  min-height: 0; /* 在 flex 布局中，需要设置 min-height: 0 才能让滚动条正常工作 */
}

/* 确保滚动条可见（Webkit浏览器） */
.messages-container::-webkit-scrollbar {
  width: 8px;
}

.messages-container::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 4px;
}

.messages-container::-webkit-scrollbar-thumb {
  background: #888;
  border-radius: 4px;
}

.messages-container::-webkit-scrollbar-thumb:hover {
  background: #555;
}

.message-item {
  display: flex;
  margin-bottom: 15px;
  align-items: flex-start;
  gap: 10px;
}

.message-item.user {
  flex-direction: row-reverse;
}

.message-item.system {
  justify-content: center;
  margin-bottom: 10px;
}

.message-item .avatar {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 18px;
  flex-shrink: 0;
  background: #e3f2fd;
}

.message-item.user .avatar {
  background: #007AFF;
}

.message-content {
  max-width: 70%;
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.message-item.user .message-content {
  align-items: flex-end;
}

.message-item.bot .message-content {
  align-items: flex-start;
}

.message-item.system .message-content {
  align-items: center;
  max-width: 100%;
}

.message-bubble {
  padding: 10px 14px;
  border-radius: 18px;
  word-wrap: break-word;
  line-height: 1.4;
}

.message-bubble.user {
  background: #007AFF;
  color: white;
  border-bottom-right-radius: 4px;
}

.message-bubble.bot {
  background: white;
  color: #333;
  border: 1px solid #e0e0e0;
  border-bottom-left-radius: 4px;
}

.message-bubble.system {
  background: transparent;
  color: #999;
  font-size: 12px;
  padding: 4px 8px;
}

.message-time {
  font-size: 11px;
  color: #999;
  padding: 0 5px;
}

.typing-indicator {
  display: flex;
  gap: 4px;
  align-items: center;
  padding: 10px;
}

.typing-indicator span {
  width: 8px;
  height: 8px;
  background: #999;
  border-radius: 50%;
  animation: typing 1.4s infinite;
}

.typing-indicator span:nth-child(2) {
  animation-delay: 0.2s;
}

.typing-indicator span:nth-child(3) {
  animation-delay: 0.4s;
}

@keyframes typing {
  0%, 60%, 100% {
    transform: translateY(0);
    opacity: 0.7;
  }
  30% {
    transform: translateY(-10px);
    opacity: 1;
  }
}

.input-area {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 12px 15px;
  background: white;
  border-top: 1px solid #f0f0f0;
}

.message-input {
  flex: 1;
  padding: 10px 15px;
  border: 1px solid #e0e0e0;
  border-radius: 20px;
  font-size: 14px;
  outline: none;
}

.message-input:focus {
  border-color: #007AFF;
}

.message-input:disabled {
  background: #f5f5f5;
  cursor: not-allowed;
}

.send-btn {
  padding: 10px 20px;
  background: #007AFF;
  color: white;
  border: none;
  border-radius: 20px;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s;
}

.send-btn:hover:not(:disabled) {
  background: #0056b3;
}

.send-btn:disabled {
  background: #ccc;
  cursor: not-allowed;
}
</style>

